package club.banyuan.demo.sec.controller;

import club.banyuan.demo.sec.common.ApiResponse;
import club.banyuan.demo.sec.config.security.JwtUtils;
import club.banyuan.demo.sec.dto.LoginParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private Logger LOGGER = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 登录
     */
    @PostMapping("/login")
    public ApiResponse login(@Valid @RequestBody LoginParams loginParams) {
        try {
            Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginParams.getUsername(), loginParams.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authentication);

            String token = jwtUtils.createJWT(authentication, loginParams.getRememberMe());

            Map<String, String> info = new HashMap<>();
            info.put("token", token);
            return ApiResponse.success(info);
        } catch (BadCredentialsException e) {
            LOGGER.warn(e.getMessage());
            return ApiResponse.failed("用户名或密码错误!");
        }
    }

    @PostMapping("/logout")
    public ApiResponse logout(HttpServletRequest request) {
        try {
            // 设置JWT过期
            jwtUtils.invalidateJWT(request);
        } catch (SecurityException e) {
            return ApiResponse.forbidden("请先登录");
        }
        return ApiResponse.success("退出成功");
    }
}
